/**
 * 无纸化维保
 */
import {Component, EventEmitter, Output} from "@angular/core";

import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService} from "ng-zorro-antd";
import * as moment from "moment";
import {HttpServcie} from "../../../../service/http.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ContractBean} from "../../../contract/bean/contract.bean";
import {ElevatorInfoBean} from "../../../elevator/elevator-info/bean/elevatorInfo.bean";
import {PaperlessMaintApplyBean} from "../../bean/paperlessMaint-apply.bean";
import {element} from "protractor";
import {elevatorTypes} from "../../../../service/constant/elevatorTypeConstant";

@Component({
  selector: "papelessMaint-add",
  templateUrl: "paperlessMaint-add.html",
  styleUrls: ["paperlessMaint-add.scss"]
})

export class PaperlessMaintAdd {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService,
    private fb: FormBuilder
  ) {

  }

  @Output() outValue = new EventEmitter();
  validateForm: FormGroup;
  // //业务参数
  // applyStatus = Config.APPLY_STATUS;  //按需维保申请状态
  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();
  papelessMaintBean : PaperlessMaintApplyBean = new PaperlessMaintApplyBean();
  user : any;
  partyType : string;
  userPartyList : any; //获取与当前维保单位有合同的使用单位
  createList : any = []; //获取当前使用单位电梯台账所有的制造单位
  //获取电梯参数
  elevatorList : any = [];
  total = 0;
  createCompanyName : any = []; //制造单位
  jgPartyList : any = []; //申请对象，所有区级监管单位

  showFlag : boolean;
  //多选框
  allChecked: any = false;
  indeterminate: any = false;
  elevatorIds  = [];

  //模态框参数
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;
  updateData: any = {};
  elevatorTypes = elevatorTypes;
  ngOnInit(){
    this.validateForm = this.fb.group({
      userPartyId : [null, [Validators.required]], //使用单位
      maintenancePartyId: [null, [Validators.required]], //维保单位
      createCompanyName : [null, [Validators.required]], //制造单位
      jgPartyId : [null, [Validators.nullValidator]], //监管单位
      outsidenumStr : [null, []],
    });
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.partyType = this.user.partyType;
    this.papelessMaintBean.maintenancePartyId = this.user.partyId;
    this.papelessMaintBean.maintenancePartyName = this.user.partyName;

    let contractBean = new ContractBean();
    contractBean.partyId  = this.user.partyId;
    contractBean.partyType = this.user.partyType;
    //查询与当前维保单位有合同关系的使用单位
    this.httpService.contractQueryByPartyIdList(contractBean).subscribe(data => {
      if (data.status === 200) {
        this.userPartyList = data.data.list;
      } else if (data.status === 401) {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }
    });

    //获取与使用单位有关系的制造单位
    let  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();
    elevatorInfo.maintenancePartyId = this.user.partyId;
    this.httpService.elevatorCreateCompany(elevatorInfo).subscribe(data => {
      if (data.status === 200) {
        let tempList = data.data.list;
        tempList.forEach(ele =>{
          this.createList.push({"value":ele});
        });

      } else if (data.status === 401) {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }
    });
  }

  submitForm() {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }

    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }

    if(this.elevatorIds.length == 0){
      this._notification.create("error", "错误提示", "电梯列表为空，重新选择申请条件；或者电梯已经被申请过，且审批通过");
      return;
    }
    //取得选择的电梯
    this.papelessMaintBean.elevatorIds = this.elevatorIds.join(",");
    /**
     * 获取当前使用单位的上级监管单位与上上级监管单位
     */
    this.httpService.partyQueryById({ id: this.user.partyParentId }).subscribe(data => {
      if (data.status == 200) {
        this.papelessMaintBean.applyStatus = '0';
        this.papelessMaintBean.parentParentPartyId = data.data.parentId;
        this.httpService.addPaperlessMaintance(this.papelessMaintBean).subscribe(data => {
          if (data["status"] != "200") {
            this._notification.create("error", "错误提示", "新增失败！");
            return;
          }
          this.outValue.emit(true);
        });
      }else{
        this._notification.create("error", "错误提示", "查询失败！");
        return;
      }
    });
  }

  quit() {
    this.outValue.emit(true);
  }

  /**
   * 获取使用单位名称
   */
  getUserParty(){
    if(this.userPartyList){
      console.log("userPartyList" + this.userPartyList);
      this.userPartyList.forEach(element =>{
        if(this.papelessMaintBean.userPartyId == element.firstParty){
          this.papelessMaintBean.userPartyName = element.firstPartyName;
        }
      })
    }
  }

  /**
   * 处理制造单位
   * @param name
   */
  getCreateCompanyName(){
    if(!this.papelessMaintBean.userPartyId || !this.papelessMaintBean.maintenancePartyId){
      this._notification.create("error", "错误提示", "请先填写单位相关信息！");
      return;
    }
    if(this.createCompanyName){
      this.papelessMaintBean.createCompanyName = this.createCompanyName.join(",");
    }
    if(this.createCompanyName.length == 0){
      return;
    }
    this.elevatorInfo.usedPartyId = this.papelessMaintBean.userPartyId;
    this.elevatorInfo.maintenancePartyId = this.papelessMaintBean.maintenancePartyId;
    this.elevatorInfo.createCompanyName = this.papelessMaintBean.createCompanyName;
    this.httpService.getOptionalJgParty(this.elevatorInfo).subscribe(data=>{
      if(data.status == 200){
        this.jgPartyList = data.data;
      }else{
        this._notification.create("error", "错误提示", "查询失败");
      }
    })
  }

  /**
   * 获取申请对象单位名称
   * @param name
   */
  getJgPartyName(){
    this.elevatorIds = [];
    if(!this.papelessMaintBean.userPartyId || !this.papelessMaintBean.maintenancePartyId || this.createCompanyName.length == 0){
      this._notification.create("error", "错误提示", "请先填写单位相关信息！");
      return;
    }

    if(this.jgPartyList){
      this.jgPartyList.forEach(element =>{
        if(this.papelessMaintBean.jgPartyId == element.id){
          this.papelessMaintBean.jgPartyName = element.partyName;
          if(element.isNotMaintCount != 0 && element.isMaintCount > 0){
            this._notification.create("error", "错误提示", "当前条件下，查出的电梯未完成两次维保作业");
            this.showFlag = false;
            return;
          }
          //符合条件，获取旗下所有电梯参加无纸化维保
          this.queryElevator();
        }
      });
    }

  }

  getFormControl(name){
    return this.validateForm.controls[name];
  }

  addElevator(title, content, footer){
    if (this.partyType != '1') {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }

    this.elevatorInfo.pageSize = 10;
    this.elevatorInfo.currentPage = 1;
    this.modelTitle = "添加电梯";
    this.modal = 0;
    console.log(this.createCompanyName.length);
    if(!this.papelessMaintBean.jgPartyId){
      this._notification.create("error", "错误提示", "请先填写申请对象！");
      return;
    }
    this.queryElevator();
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 1200,
      zIndex: 2000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }


  /**
   * 获取电梯
   */
  queryElevator(){
    this.elevatorIds = []; //初始化电梯列表
    this.elevatorInfo.usedPartyId = this.papelessMaintBean.userPartyId;
    this.elevatorInfo.maintenancePartyId = this.papelessMaintBean.maintenancePartyId;
    this.elevatorInfo.createCompanyName = this.papelessMaintBean.createCompanyName;
    this.elevatorInfo.jgPartyId = this.papelessMaintBean.jgPartyId;
    this.httpService.paperlessMaintGetElevators(this.elevatorInfo).subscribe(
      data => {
        if (data.status == 200) {
          this.elevatorList = data.data.list;
          this.total = data.data.total;
          this.elevatorList.forEach(element1 => {
            let isNotExist = true;
            this.elevatorIds.forEach(element2 => {
              if(element1.id == element2){
                isNotExist = false;
              }
            });
            if(isNotExist){
              this.elevatorIds.push(element1.id + "");
            }
          });
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 保存勾选的电梯
   */
 /* saveElevators(){

    //再次点击时重新给值
    let isNo = false;
    const tempList: any = [];
    this.elevatorList.forEach(element => {
      let isNotExist = true;
      if (element.checked) {
        if(element.isMaint == '否'){
          isNo = true;
        }
        if(!isNo){
          tempList.push(element);
          this.elevatorIds.forEach(element1 =>{
            if(element.id == element1){
              isNotExist = false;
            }
          });
          if(isNotExist){
            // this.papelessMaintBean.outsidenumStr = this.papelessMaintBean.outsidenumStr + element.outsideNum + ",";
            this.elevatorIds.push(element.id + "");
          }
        }
      }
    });
    this.papelessMaintBean.elevatorIds = this.elevatorIds.join(",");
    if(isNo){
      this._notification.create("error", "错误提示", "请选择维保次数两次及两次以上的电梯！");
      return;
    }
    if (tempList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "至少选中一条数据！");
      return;
    }

    this.currentModal.destroy();
  }*/

  clear(){
    this.papelessMaintBean.elevatorIds = "";
    this.elevatorIds.splice(0,this.elevatorIds.length);
  }

  //添加返回
  addCall(event) {
    this.currentModal.destroy();
  }


  //table加载数据时
  displayDataChange($event) {
    this.elevatorList = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.elevatorList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.elevatorList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.elevatorList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.elevatorList.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.elevatorInfo.pageSize = event;
    this.elevatorInfo.currentPage = 1;
    this.queryElevator();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.elevatorInfo.currentPage = event;
    this.queryElevator();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.elevatorInfo.currentPage = event;
    this.queryElevator();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

}
